<?php

declare(strict_types=1);

namespace App\Model;

use App\Util\ImUtil;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * 用户冻结log
 */
class UserFreezeLog extends Model
{
    protected $table = 'user_freeze_log';

    protected $fillable = [
        'user_id', 'act', 'flag', 'reason_type', 'reason'
    ];

    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    protected function serializeDate(\DateTimeInterface $date){
        return $date->format('Y-m-d H:i:s');
    }

    const REASON_TYPE = [
        0 => '其他',
        1 => '脚本聊天',
        2 => '广告',
        3 => '涉黄',
        4 => '恶意退款',
        5 => '涉政',
        6 => '虚假消息',
        7 => '低俗',
        8 => '未成年',
    ];

    public function userProfile()
    {
        return $this->belongsTo(UserProfile::class, 'user_id', 'user_id');
    }

    public function adminUser()
    {
        return $this->belongsTo(AdminUsers::class, 'op_admin_id', 'id');
    }

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    /**
     * 添加数据
     */
    static function addRecord($userId = 0, $reasonType, $act = 1, $reason = '')
    {
        return self::create([
            'user_id' => $userId,
            'act' => $act,
            'reason_type' => $reasonType ?: 0,
            'reason' => $reason ?: ''
        ]);
    }

    /**
     * 查询冻结原因
     */
    static function checkReason($userId)
    {
        $where = [
            'user_id' => $userId,
            'act' => 1,
        ];
        $item = self::where($where)->orderBy('id', 'desc')->first();
        if (!$item) return '';
        return [
            // 'text' => self::REASON_TYPE[$item->reason_type] . '：' . $item->reason,
            'count' => self::where($where)->count()
        ];
    }

    /**
     * 封禁IP
     * @param $ip
     * @return string
     */
    public function freezeIp($ip)
    {
        $clientIp = $ip;
        $userIds = User::where('client_ip', $clientIp)->pluck('id')->toArray();
        $count  = count($userIds);
        if ($count > 50) {
            return '用户数量超过50个，请一一操作';
        }

        User::whereIn('id', $userIds)->limit($count)->update(['status' => User::STATUS_FREEZE]);

        //加入IP黑名单
        IpBlacklist::addIp($clientIp);

        Log::info(__METHOD__ . "==Action:{freezeIp}=={$clientIp}==" . json_encode($userIds));

        return 'ok';
    }
}
